//
//  GSDKUserDataController.m
//  GameSDK
//
//  Created by Johnny on 2017/7/31.
//  Copyright © 2017年 Johnny. All rights reserved.
//

#import "GSDKUserDataController.h"
#import "GSDKDatabaseManager.h"
#import "GSDKCommonMethod.h"
#import "GSDKUserConfig.h"
#import "NSUserDefaults+Extension.h"
#import "GSDKUserAccountModel.h"
#import "GSDKKeyChainHelper.h"
#import "GSDKComplatformBase.h"
#import "GSDKEncryptionHelper.h"
#import "GSDKServicesManager.h"
#import "NSPredicate+Extension.h"
#import "YYKit.h"
#import <FBSDKCoreKit/FBSDKCoreKit.h>
#import <FBSDKLoginKit/FBSDKLoginKit.h>
#import "UIViewController+Extension.h"
#import "NSString+Extension.h"
#import "UIView+Extension.h"
#import <GoogleSignIn/GoogleSignIn.h>
#import "WXApi.h"
#import "GSDKServicesManager.h"
@interface GSDKUserDataController () <GIDSignInUIDelegate, GIDSignInDelegate>
@property (nonatomic, copy) GSDKCompletionBlock completionBlock;
@property (nonatomic, copy) GSDKFailureBlock failureBlock;
@end

@implementation GSDKUserDataController
- (void)dealloc {
    [GIDSignIn sharedInstance].uiDelegate = nil;
    [GIDSignIn sharedInstance].delegate = nil;
    DEBUGMSG(@"GSDKUserDataController dealloc");
}

- (NSArray *)getAllAccounds {
    return [[[[GSDKDatabaseManager shared] selectUserWith:nil] reverseObjectEnumerator] allObjects];
}

- (void)getDefaultUserAt:(void(^)(GSDKUserAccountModel * userAccount))userBlock {
    GSDKUserAccountModel * userAccount = nil;
    NSArray *array = [[NSArray alloc] initWithArray:[[GSDKDatabaseManager shared] selectUserWith:[NSUserDefaults getValueIn:USERNAME]]];
    userAccount = [array firstObject];
    if (userAccount == nil) {
        if ([GSDKKeyChainHelper getValueIn:[NSString stringWithFormat:@"%@%@", GSDKINITCONFIGURE.gid, ACCOUNTKEY]] != nil) {
            userAccount = [GSDKUserAccountModel modelWithJSON:[GSDKEncryptionHelper decodeBase64WithString:[GSDKKeyChainHelper getValueIn:[NSString stringWithFormat:@"%@%@", GSDKINITCONFIGURE.gid, ACCOUNTKEY]]]];
        }
    }
    userBlock(userAccount);
}

- (void)getAccountUserAt:(void(^)(GSDKUserAccountModel * userAccount))userBlock {
    GSDKUserAccountModel * userAccount = nil;
    NSArray *array = [[NSArray alloc] initWithArray:[[GSDKDatabaseManager shared] selectUserWith:[NSUserDefaults getValueIn:USERNAME]]];
    for (GSDKUserAccountModel * account in array) {
        if ((ThirdPartyLoginType)account.type == ThirdPartyLoginTypeEmail || (ThirdPartyLoginType)account.type == ThirdPartyLoginTypeName) {
            userAccount = account;
            break;
        }
    }
    if (userAccount == nil) {
        NSArray *array = [[NSArray alloc] initWithArray:[[GSDKDatabaseManager shared] selectUserWith: nil]];
        for (GSDKUserAccountModel * account in array) {
            if ((ThirdPartyLoginType)account.type == ThirdPartyLoginTypeEmail || (ThirdPartyLoginType)account.type == ThirdPartyLoginTypeName) {
                userAccount = account;
                break;
            }
        }
    }
    
    if (userAccount == nil) {
        if ([GSDKKeyChainHelper getValueIn:[NSString stringWithFormat:@"%@%@", GSDKINITCONFIGURE.gid, ACCOUNTKEY]] != nil) {
            userAccount = [GSDKUserAccountModel modelWithJSON:[GSDKEncryptionHelper decodeBase64WithString:[GSDKKeyChainHelper getValueIn:[NSString stringWithFormat:@"%@%@", GSDKINITCONFIGURE.gid, ACCOUNTKEY]]]];
        }
    }
    userBlock(userAccount);
}

- (void)saveUserDataWithUserName:(NSString *)userName
                    withPassword:(NSString *)password
                       withToken:(NSString *)token
                         withUid:(NSString *)uid
                        withType:(ThirdPartyLoginType)type
                       withOther:(NSString *)other {
    if (GSDKCOMMONMETHOD.accountModel != nil) {
        [NSUserDefaults removeValueIn:ISLOGIN];
        GSDKCOMMONMETHOD.accountModel = nil;
        
        GSDKAccountStatus * user = [[GSDKAccountStatus alloc] init];
        user.gSDKAccountStatus = GSDK_ACCOUNT_STATUS_LOGOUT;
        GSDKMessageStatus * message = [[GSDKMessageStatus alloc] init];
        message.code = @"0";
        message.msg = [NSString localizedStringForKey:@"GSDK_logoutsuccess_text" value:@"注销成功"];
        [[NSNotificationCenter defaultCenter] postNotificationName:GSDKUserDidFinishNotification object:nil userInfo:@{@"GSDKAccountStatus": user, @"GSDKMessageStatus": message}];
        
        [[GSDKServicesManager new] oneTimeRequest:[[GSDKLogoutModel alloc] initWithToken:GSDKCOMMONMETHOD.GSDKToken] andCompletionBlock:^(id responseObject) {
            DEBUGMSG(@"responseObject = %@", responseObject);
        }];
    }
    
    GSDKUserAccountModel * model = [GSDKUserAccountModel new];
    model.userName = userName;
    model.uid = uid;
    model.passWord = password;
    model.token = token;
    model.type = type;
    model.other = other;
    
    [NSUserDefaults saveValue:userName withKey:USERNAME];
    [NSUserDefaults saveValue:@"1" withKey:ISLOGIN];
    
    GSDKCOMMONMETHOD.accountModel = model;
    
    [[GSDKDatabaseManager shared] insertUserWith:model];
    [GSDKKeyChainHelper saveValue:[GSDKEncryptionHelper encryptBase64WithString:[model modelToJSONString]] withKey:[NSString stringWithFormat:@"%@%@", GSDKINITCONFIGURE.gid, ACCOUNTKEY]];
    
    
}

- (void)registeredWithUsername:(NSString *)username
                  withPassword:(NSString *)password
                     withToken:(NSString *)token
                      withType:(ThirdPartyLoginType)type
                 withSaveAlbum:(BOOL)isSave
           withCompletionBlock:(GSDKCompletionBlock)completion
              withFailureBlock:(GSDKFailureBlock)failure {
    if (type == ThirdPartyLoginTypeEmail) {
        if (![[NSPredicate new] evaluateEmail:username]) {
            failure([NSString localizedStringForKey:@"GSDK_email_error" value:@"邮箱格式错误"]);
            return;
        }
    } else {
        if ([username length] > 16 || [username length] < 6 || ![[NSPredicate new] evaluateValue:username withRegex:@"^[A-Za-z0-9-_]+$"]) {
            failure([NSString localizedStringForKey:@"GSDK_username_error" value:@"用户名只能是6~12位字母、数字和下划线"]);
            return;
        }
    }
    if ([password length] > 16 || [password length] < 6 || ![[NSPredicate new] evaluateValue:password withRegex:@"^[A-Za-z0-9-_]+$"]) {
        failure([NSString localizedStringForKey:@"GSDK_password_error" value:@"密码只能是6~16位字母、数字和下划线"]);
        return;
    }
    
    GSDKRegisterModel * model = [[GSDKRegisterModel alloc] initWithUserName:username
                                                               withPassword:password
                                                                  withToken:token
                                                                   withType:[NSString stringWithFormat:@"%lu", (unsigned long)type]];
    [[GSDKServicesManager new] request:model andCompletionBlock:^(id responseObject) {
        GSDKResLoginModel * model = [GSDKResLoginModel modelWithJSON:responseObject];
        if ([model.code isEqualToString:@"0"]) {
            [[GSDKUserDataController new] saveUserDataWithUserName:model.user_name withPassword:password withToken:model.login_token withUid:model.uid withType:type withOther:@""];
            completion(model);
            if (isSave) {
                [self saveScreenshotWithUserName:username andPassWork:password];
            }
        } else {
            failure(model.message);
        }
    }];
}

- (void)loginWithUsername:(NSString *)username
             withPassword:(NSString *)password
                withToken:(NSString *)token
                 withType:(ThirdPartyLoginType)type
                withOther:(NSString *)other
      withCompletionBlock:(GSDKCompletionBlock)completion
         withFailureBlock:(GSDKFailureBlock)failure {
    if (type == ThirdPartyLoginTypeEmail || type == ThirdPartyLoginTypeName) {
        if ([username length] == 0) {
            failure([NSString localizedStringForKey:@"GSDK_username_empty" value:@"用户名不能为空"]);
            return;
        }
        if ([password length] > 16 || [password length] < 6 || ![[NSPredicate new] evaluateValue:password withRegex:@"^[A-Za-z0-9-_]+$"]) {
            failure([NSString localizedStringForKey:@"GSDK_password_error" value:@"密码只能是6~16位字母、数字和下划线"]);
            return;
        }
    }
    
    GSDKLoginModel * model = [[GSDKLoginModel alloc] initWithUserName:username
                                                         withPassword:password
                                                            withToken:token
                                                             withType:[NSString stringWithFormat:@"%lu", type]
                                                            withOther:other];
    [[GSDKServicesManager new] request:model andCompletionBlock:^(id responseObject) {
        GSDKResLoginModel * model = [GSDKResLoginModel modelWithJSON:responseObject];
        if ([model.code isEqualToString:@"0"]) {
            [[GSDKUserDataController new] saveUserDataWithUserName:model.user_name withPassword:password withToken:model.login_token withUid:model.uid withType:type withOther:other];
            completion(model);
        } else {
            failure(model.message);
        }
    }];
}

- (void)thirdPartyLogin:(ThirdPartyLoginType)type
    withCompletionBlock:(GSDKCompletionBlock)completion
       withFailureBlock:(GSDKFailureBlock)failure {
    if (type == ThirdPartyLoginTypeFacebook) {
        FBSDKLoginManager *login = [[FBSDKLoginManager alloc] init];
        [login
         logInWithReadPermissions: @[@"public_profile"]
         fromViewController:[UIViewController getCurrentRootViewController]
         handler:^(FBSDKLoginManagerLoginResult *result, NSError *error) {
             if (error) {
                 failure(error.localizedDescription);
             } else if (result.isCancelled) {
                 failure([NSString localizedStringForKey:@"GSDK_login_error" value:@"登录失败"]);
             } else {
                 completion(@{@"appID": [result.token appID], @"tokenString": [result.token tokenString], @"userID": [result.token userID]});
             }
         }];
    }
    if (type == ThirdPartyLoginTypeGoogleplus) {
        self.completionBlock = completion;
        self.failureBlock = failure;
        
        [GIDSignIn sharedInstance].uiDelegate = self;
        [GIDSignIn sharedInstance].delegate = self;
        
        [[GIDSignIn sharedInstance] signOut];
        [[GIDSignIn sharedInstance] signIn];
    }
    if (type == ThirdPartyLoginTypeWechat) {
        self.completionBlock = completion;
        self.failureBlock = failure;
        
        SendAuthReq * req = [SendAuthReq new];
        req.scope = @"snsapi_userinfo";
        req.state = @"0c806938e2413ce73eef92cc3";
        req.openID = @"owJ6vjljAu5MLCL9DBdtgEgay8EQ";
        [WXApi sendReq:req];
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(wechatHandle:) name:@"wechatHandleNotificationName" object:nil];
    }
}

- (void)wechatHandle:(NSNotification *)noti {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"wechatHandleNotificationName" object:nil];
    SendAuthResp * sendResp = (SendAuthResp *)[noti object];
    if (sendResp.code == nil) {
        self.failureBlock([NSString localizedStringForKey:@"GSDK_login_error" value:@"登录失败"]);
        return;
    }
    __weak GSDKUserDataController* bSelf = self;
    NSString * string = [[NSString alloc] initWithFormat:@"https://api.weixin.qq.com/sns/oauth2/access_token?appid=%@&secret=%@&code=%@&grant_type=authorization_code", GSDKCOMMONMETHOD.WXAppId, GSDKCOMMONMETHOD.WXsecret, sendResp.code];
    [[GSDKServicesManager new] urlRequest:string completionBlock:^(id responseObject) {
        GSDKWeChatModel * model = [GSDKWeChatModel modelWithJSON:responseObject];
        if (model == nil) {
            bSelf.failureBlock([NSString localizedStringForKey:@"GSDK_login_error" value:@"登录失败"]);
            return ;
        }
        self.completionBlock([model modelToJSONObject]);
    } failureBlock:^{
        bSelf.failureBlock([NSString localizedStringForKey:@"GSDK_login_error" value:@"登录失败"]);
    }];
}

- (void)getNameWithToken:(NSString *)token
     withCompletionBlock:(GSDKCompletionBlock)completion
        withFailureBlock:(GSDKFailureBlock)failure {
    GSDKGetNameModel * model = [[GSDKGetNameModel alloc] initWithToken:token];
    [[GSDKServicesManager new] request:model andCompletionBlock:^(id responseObject) {
        GSDKResGetnameModel * model = [GSDKResGetnameModel modelWithJSON:responseObject];
        if ([model.code isEqualToString:@"0"]) {
            model.password = [NSString getRandomPassword:6];
            completion(model);
        } else {
            failure(model.message);
        }
    }];
}

/**
 *  保存首次登录界面，随机账号和密码截图
 *
 *  @param userName 随机账号
 *  @param passWork 随机密码
 */
- (void)saveScreenshotWithUserName:(NSString*)userName andPassWork:(NSString*)passWork {
    UIView * screenshotView = [[UIView alloc]init];
    [screenshotView setBackgroundColor:[UIColor whiteColor]];
    [screenshotView setFrame:CGRectMake(0, 0, 380, 320)];
    
    UIImageView * imageView = [[UIImageView alloc]initWithFrame:screenshotView.frame];
    [imageView setImage:[UIImage imageNamed:@"ZYSDK_Resourcres.bundle/pic/FYSDK_Screenshot"]];
    [screenshotView addSubview:imageView];
    
    UILabel * unLabel = [[UILabel alloc] init];
    unLabel.text = userName;
    [unLabel setNumberOfLines:1];
    [unLabel setFont:[UIFont systemFontOfSize:15]];
    unLabel.textColor = [UIColor blackColor];
    [unLabel setAlpha:0.6];
    [unLabel setBackgroundColor:[UIColor clearColor]];
    [unLabel setFrame:CGRectMake(88,84,257,45)];
    [screenshotView addSubview:unLabel];
    
    UILabel * pwLabel = [[UILabel alloc] init];
    pwLabel.text = passWork;
    [pwLabel setNumberOfLines:1];
    [pwLabel setFont:[UIFont systemFontOfSize:15]];
    pwLabel.textColor = [UIColor blackColor];
    [pwLabel setAlpha:0.6];
    [pwLabel setBackgroundColor:[UIColor clearColor]];
    [pwLabel setFrame:CGRectMake(88,152,257,45)];
    [screenshotView addSubview:pwLabel];
    
    UIImageWriteToSavedPhotosAlbum([screenshotView getImage], self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);
}
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
    if(error == NULL){
        UIAlertView * alertView = [[UIAlertView alloc]initWithTitle:nil message:[NSString localizedStringForKey:@"GSDK_savealbum_text" value:@"账号密码已保存至相册"] delegate:nil cancelButtonTitle:[NSString localizedStringForKey:@"GSDK_cancel_text" value:@"取消"] otherButtonTitles:nil, nil];
        [alertView show];
    }
}

- (void)signInWillDispatch:(GIDSignIn *)signIn error:(NSError *)error {}

- (void)signIn:(GIDSignIn *)signIn presentViewController:(UIViewController *)viewController {
    [[UIViewController getCurrentRootViewController] presentViewController:viewController animated:YES completion:nil];
}

- (void)signIn:(GIDSignIn *)signIn dismissViewController:(UIViewController *)viewController {
    [[UIViewController getCurrentRootViewController] dismissViewControllerAnimated:YES completion:nil];
}

- (void)signIn:(GIDSignIn *)signIn didSignInForUser:(GIDGoogleUser *)user withError:(NSError *)error {
    // Perform any operations on signed in user here.
    if (error != nil) {
        self.failureBlock([NSString localizedStringForKey:@"GSDK_login_error" value:@"登录失败"]);
        return;
    }
    self.completionBlock(@{@"userID": user.userID});
}
- (void)signIn:(GIDSignIn *)signIn didDisconnectWithUser:(GIDGoogleUser *)user withError:(NSError *)error {}
@end
